<template>
  <div class="image-field">
    <!-- 缩略 + hover 预览 -->
    <div v-if="displayUrl" class="thumb-wrapper">
      <div class="thumb" :style="thumbStyle">
        <img :src="displayUrl" alt="" />
      </div>
      <div class="hover-preview">
        <div class="preview-box" :style="trueSizeStyle">
          <img :src="displayUrl" alt="" />
          <div class="ruler">{{ local.widthCm || 0 }}cm × {{ local.heightCm || calcHeightCm }}</div>
        </div>
      </div>
    </div>
    <!-- 前后说明文字 + 名称在属性面板中配置，此处仅显示缩略及基本信息 -->
    <div class="uploader-row">
      <el-upload
        class="upload"
        :show-file-list="false"
        :http-request="handleCustomUpload"
        accept="image/png,image/jpeg,image/webp"
      >
        <el-button type="primary" size="small">上传图片</el-button>
      </el-upload>
    </div>

    <div class="size-row">
      <el-form-item label="宽度(cm)">
        <el-input-number v-model="local.widthCm" :min="1" :max="30" :precision="2" controls-position="right" />
      </el-form-item>
      <el-form-item label="高度(cm)">
        <el-input-number v-model="local.heightCm" :min="0" :max="30" :precision="2" controls-position="right" />
      </el-form-item>
      <el-switch v-model="local.maintainAspectRatio" active-text="保持比例" />
    </div>
  </div>
  
</template>

<script setup>
import { reactive, watch, computed } from 'vue'
import { ElUpload, ElButton, ElFormItem, ElInputNumber, ElSwitch, ElMessage } from 'element-plus'
import { api } from '@/utils/api'

const props = defineProps({
  modelValue: { type: Object, required: true }
})
const emit = defineEmits(['update:modelValue'])

const local = reactive({
  widthCm: props.modelValue?.image?.widthCm ?? 8,
  heightCm: props.modelValue?.image?.heightCm ?? null,
  maintainAspectRatio: props.modelValue?.image?.maintainAspectRatio ?? true
})

watch(local, () => {
  const next = {
    ...(props.modelValue || {}),
    image: {
      ...(props.modelValue?.image || {}),
      widthCm: local.widthCm,
      heightCm: local.heightCm,
      maintainAspectRatio: local.maintainAspectRatio
    }
  }
  emit('update:modelValue', next)
}, { deep: true })

const thumbStyle = computed(() => ({
  maxWidth: '180px',
  maxHeight: '120px',
}))

const displayUrl = computed(() => props.modelValue?.image?.previewUrl || props.modelValue?.image?.url || '')

// 按 96DPI 将 cm 转 px
const cmToPx = (cm) => {
  const dpi = 96
  const inch = (cm || 0) / 2.54
  return `${inch * dpi}px`
}

// hover 预览使用 1:1 厘米尺寸
const trueSizeStyle = computed(() => ({
  width: cmToPx(local.widthCm || 0),
  height: local.heightCm ? cmToPx(local.heightCm) : 'auto'
}))

const calcHeightCm = computed(() => local.maintainAspectRatio && !local.heightCm ? (Math.round((local.widthCm || 0) * 100) / 100) : local.heightCm)

const handleCustomUpload = async ({ file }) => {
  try {
    const res = await api.uploads.uploadImage(file)
    const data = res.data
    const next = {
      ...(props.modelValue || {}),
      image: {
        ...(props.modelValue?.image || {}),
        url: data.url,
        previewUrl: data.absoluteUrl || data.url,
        mime: data.mime,
        widthCm: local.widthCm,
        heightCm: local.heightCm,
        maintainAspectRatio: local.maintainAspectRatio
      }
    }
    emit('update:modelValue', next)
    ElMessage.success('上传成功')
  } catch (e) {
    ElMessage.error(e?.message || '上传失败')
  }
}
</script>

<style scoped>
.image-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.thumb-wrapper { position: relative; display: inline-block; }
.uploader-row {
  display: flex;
  align-items: center;
  gap: 12px;
}
.thumb img {
  display: block;
  max-width: 180px;
  max-height: 120px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
}
.hover-preview { display: none; position: absolute; left: 0; top: 100%; margin-top: 8px; padding: 8px; background: rgba(255,255,255,.98); border: 1px solid #e5e7eb; border-radius: 6px; box-shadow: 0 6px 20px rgba(0,0,0,.12); z-index: 20; }
.thumb-wrapper:hover .hover-preview { display: block; }
.preview-box { position: relative; }
.preview-box img { display: block; width: 100%; height: 100%; object-fit: contain; }
.ruler { position: absolute; right: 6px; bottom: 6px; font-size: 12px; color: #111; background: rgba(255,255,255,.9); padding: 2px 6px; border-radius: 4px; border: 1px solid #e5e7eb; }
.size-row {
  display: flex;
  align-items: center;
  gap: 12px;
}
</style>

